package com.example.app18_service_client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private EditText et_main;

    private ServiceConnection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");

        et_main = findViewById(R.id.et_main);
    }

    /**
     * 绑定远程Service
     * @param view view
     */
    public void bindRemoteService(View view) {
        Intent intent = new Intent("com.example.app18_service.service.MyRemoteService.Action");
        if (conn == null) {
            conn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Log.i(TAG, "onServiceConnected()");
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    Log.i(TAG, "onServiceDisconnected()");
                }
            };
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "绑定Service...", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已绑定Service...", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 调用远程服务
     * @param view view
     */
    public void invokeRemoteService(View view) {

    }

    /**
     * 解绑远程服务
     * @param view view
     */
    public void unbindRemoteService(View view) {
        if (conn != null) {
            unbindService(conn);
            conn = null;
            Toast.makeText(this, "解除绑定Service...", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已绑定Service...", Toast.LENGTH_SHORT).show();
        }
    }
}